//
//  ViewController.m
//  VoiceWakeUp
//
//  Created by Feng on 2019/3/5.
//  Copyright © 2019 com.orvibo.com. All rights reserved.
//

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "FGMusicModel.h"
#import "FGLogViewController.h"
#import "FGMixPadTableViewController.h"

#define MusicFilePath [NSHomeDirectory() stringByAppendingString:@"/Documents/music"]
#define LogSegueIdentifier @"gotoLogVC"
#define MixPadSegueIdentifier @"gotoMixPadVC"
#define CountDownTime 3

@interface ViewController () <UITableViewDelegate, UITableViewDataSource, AVAudioPlayerDelegate,HMBusinessProtocol>
@property (weak, nonatomic) IBOutlet UITextField *distanceTextField;
@property (weak, nonatomic) IBOutlet UITextField *angleTextField;
@property (weak, nonatomic) IBOutlet UISegmentedControl *modeSegmentedControl;
@property (weak, nonatomic) IBOutlet UITextField *timesTextField;
@property (weak, nonatomic) IBOutlet UIButton *startBtn;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *indicatorView;

@property (strong, nonatomic) AVAudioPlayer *player;
@property (strong, nonatomic) NSMutableArray *musicModelArr;
@property (assign, nonatomic) NSInteger playIndex;
@property (assign, nonatomic) NSInteger allPlayCount;
@property (assign, nonatomic) BOOL isTesting;
@property (strong, nonatomic) NSMutableString *log;
@property (assign, nonatomic) float testPercent;
@property (strong, nonatomic) NSTimer *timer;
@property (assign, nonatomic) BOOL timerStop;
@property (assign, nonatomic) int countDown;
@end

@implementation ViewController

- (void)dealloc{
    [RemoteGateway shareInstance].delegate = nil;
}

- (void)setIsTesting:(BOOL)isTesting {
    _isTesting = isTesting;
    _distanceTextField.userInteractionEnabled    = !isTesting;
    _angleTextField.userInteractionEnabled       = !isTesting;
    _modeSegmentedControl.userInteractionEnabled = !isTesting;
    _timesTextField.userInteractionEnabled       = !isTesting;
    _tableView.userInteractionEnabled            = !isTesting;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.indicatorView.hidden = YES;
    self.playIndex = -1;
    self.allPlayCount = 0;
    self.log = [NSMutableString string];
    [self loadMusic];
    
    [RemoteGateway shareInstance].delegate = self;
}

#pragma mark - 发送指令到MixPad
/**
 *  接收到任意数据时给委托对象的回调
 */
-(void)receiveDataCallback:(NSDictionary *)payloadDic
{
    if ([payloadDic[@"cmd"] intValue] == 289) {
        FGMusicModel *music = [self currentPlayMusicModel];
        NSString *name = payloadDic[@"data"][@"name"];
        BOOL wakeup = [payloadDic[@"data"][@"wakeup"] boolValue];
        if (name && [music.name isEqualToString:name] && wakeup) {
            music.successCount++;
        }
    }
}

-(void)sendCmdToMixPad:(SocketCompletionBlock)block {
    FGMusicModel *music = [self currentPlayMusicModel];
    QueryDataFromMixPadCmd *cmd = [QueryDataFromMixPadCmd object];
    cmd.uid = self.mixpad.uid;
    cmd.dataDic = @{@"type":@(11),@"name":music.name};
    sendCmd(cmd, block);
}

- (void)loadMusic {
    
    self.musicModelArr = [NSMutableArray array];
    
    NSFileManager* fm = [NSFileManager defaultManager];
    
    if(![fm fileExistsAtPath:MusicFilePath]){
        [fm createDirectoryAtPath:MusicFilePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    NSDirectoryEnumerator *dirEnum = [fm enumeratorAtPath:MusicFilePath];
    
    for (NSString *musicName in dirEnum.allObjects) {
        
        NSString *filePath = [NSString stringWithFormat:@"%@/%@",MusicFilePath, musicName];
        if ([self isDirectory:filePath]) continue;
        if ([musicName isEqualToString:@".DS_Store"]) continue;
        
        FGMusicModel *model = [[FGMusicModel alloc] init];
        model.path          = filePath;
        model.name          = musicName;
        model.successCount  = 0;
        model.playedCount   = 0;
        [self.musicModelArr addObject:model];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.musicModelArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *cellIdentifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
        cell.selectedBackgroundView.backgroundColor = [UIColor blueColor];
    }
    FGMusicModel *model = self.musicModelArr[indexPath.row];
    cell.textLabel.text = model.name;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.playIndex = indexPath.row;
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    FGMusicModel *model = [self currentPlayMusicModel];
    model.playedCount ++;
    self.allPlayCount ++;
    if (model) {
        model.distance = self.distanceTextField.text;
        model.angle = self.angleTextField.text;
        
    }
    
    if (self.modeSegmentedControl.selectedSegmentIndex == 0) {//单曲
        
        self.testPercent = (1.0 * self.allPlayCount / self.timesTextField.text.intValue) * 100;
        NSString *btnTitle = [NSString stringWithFormat:@"暂停测试(%.0f%%)",self.testPercent];
        [self.startBtn setTitle:btnTitle forState:UIControlStateNormal];
        
        if (model.playedCount == self.timesTextField.text.intValue) {
            [self startCountDown:^(NSTimer *timer) {
                self.countDown--;
                NSLog(@"单曲 结束倒计时 %d",self.countDown);
                if (self.countDown <= 0) {
                    [self.timer invalidate];
                    self.timer = nil;
                    self.isTesting = NO;
                    [self updateLogAtSingleMode:YES];
                    [self.startBtn setTitle:@"开始测试" forState:UIControlStateNormal];
                    [self performSegueWithIdentifier:LogSegueIdentifier sender:self];
                }
            }];
            return;
        }
        
        [self startCountDown:^(NSTimer *timer) {
            self.countDown--;
            NSLog(@"单曲倒计时 %d",self.countDown);
            if (self.countDown <= 0) {
                [self.timer invalidate];
                self.timer = nil;
                [self play:^(BOOL success) {
                    if (!success) {
                        self.isTesting = NO;
                        [self updateLogAtSingleMode:YES];
                        [self.startBtn setTitle:@"开始测试" forState:UIControlStateNormal];
                        [self performSegueWithIdentifier:LogSegueIdentifier sender:self];
                    }
                }];
            }
        }];
        
    }else {
        
        self.testPercent = (1.0 * self.allPlayCount / (self.timesTextField.text.intValue * self.musicModelArr.count)) * 100;
        NSString *btnTitle = [NSString stringWithFormat:@"暂停测试(%.0f%%)",self.testPercent];
        [self.startBtn setTitle:btnTitle forState:UIControlStateNormal];
        
        if (model.playedCount == self.timesTextField.text.intValue && self.playIndex == (self.musicModelArr.count - 1)) {
            [self startCountDown:^(NSTimer *timer) {
                self.countDown--;
                NSLog(@"循环 结束倒计时 %d",self.countDown);
                if (self.countDown <= 0) {
                    [self.timer invalidate];
                    self.timer = nil;
                    self.isTesting = NO;
                    [self updateLogAtSingleMode:NO];
                    [self.startBtn setTitle:@"开始测试" forState:UIControlStateNormal];
                    [self performSegueWithIdentifier:LogSegueIdentifier sender:self];
                }
            }];
            return;
        }
        
        [self startCountDown:^(NSTimer *timer) {
            self.countDown--;
            NSLog(@"循环倒计时 %d",self.countDown);
            if (self.countDown <= 0) {
                [self.timer invalidate];
                self.timer = nil;
                [self playNext:^(BOOL success) {
                    if (!success) {
                        self.isTesting = NO;
                        [self updateLogAtSingleMode:NO];
                        [self.startBtn setTitle:@"开始测试" forState:UIControlStateNormal];
                        [self performSegueWithIdentifier:LogSegueIdentifier sender:self];
                    }
                }];
            }
        }];
    }
}

- (IBAction)playBtnClicked:(UIButton *)btn {
    
    if (!self.distanceTextField.text.length) {
        [self showAlert:@"请输入距离"];
        return;
    }else if (!self.angleTextField.text.length) {
        [self showAlert:@"请输入角度"];
        return;
    }else if (!self.timesTextField.text.length) {
        [self showAlert:@"请输入次数"];
        return;
    }else if (!self.mixpad) {
        [self showAlert:@"请先选择MixPad"];
    }
    
    if (self.isTesting) {
        
        if (self.timer) {
            if (self.timerStop) {
                [self.timer setFireDate:[NSDate date]];
                self.timerStop = NO;
                NSString *btnTitle = [NSString stringWithFormat:@"暂停测试(%.0f%%)",self.testPercent];
                [self.startBtn setTitle:btnTitle forState:UIControlStateNormal];
            }else {
                [self.timer setFireDate:[NSDate distantFuture]];
                self.timerStop = YES;
                NSString *btnTitle = [NSString stringWithFormat:@"继续测试(%.0f%%)",self.testPercent];
                [self.startBtn setTitle:btnTitle forState:UIControlStateNormal];
            }
        }else {
            if (self.player.isPlaying) {
                [self.player pause];
                NSString *btnTitle = [NSString stringWithFormat:@"继续测试(%.0f%%)",self.testPercent];
                [self.startBtn setTitle:btnTitle forState:UIControlStateNormal];
            }else {
                [self.player play];
                NSString *btnTitle = [NSString stringWithFormat:@"暂停测试(%.0f%%)",self.testPercent];
                [self.startBtn setTitle:btnTitle forState:UIControlStateNormal];
            }
        }
        
    }else {
        if (self.modeSegmentedControl.selectedSegmentIndex == 0) {//单曲
            if (self.playIndex == -1) {
                [self showAlert:@"请先点击列表选择音频"];
                return;
            }
        }else {
            self.playIndex = 0;
        }
        
        [self loadMusic];
        btn.enabled = NO;
        self.indicatorView.hidden = NO;
        [self.indicatorView startAnimating];
        
        [self play:^(BOOL success) {
            if (success) {
                btn.enabled = YES;
                self.indicatorView.hidden = YES;
                [self.indicatorView stopAnimating];
                self.isTesting = YES;
                self.allPlayCount = 0;
                self.testPercent = 0;
                [self.startBtn setTitle:@"暂停测试(0%)" forState:UIControlStateNormal];
            }else {
                btn.enabled = YES;
                self.indicatorView.hidden = YES;
                [self.indicatorView stopAnimating];
            }
        }];
    }
}

- (void)play:(void(^)(BOOL success))block {
    
    if (self.playIndex >= 0 && self.playIndex < self.musicModelArr.count && self.musicModelArr.count > 0) {
        FGMusicModel *model = self.musicModelArr[self.playIndex];
        NSString *encodedfilePath = [model.path stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        NSURL *url = [NSURL URLWithString:encodedfilePath];
        [self.player stop];
        self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
        self.player.delegate = self;
        [self sendCmdToMixPad:^(KReturnValue returnValue, NSDictionary *returnDic) {
            if (returnValue == KReturnValueSuccess) {
                [self.player play];
                block(YES);
            }else if (returnValue == KReturnValueTimeout){
                [self showAlert:@"MixPad无响应"];
                block(NO);
            }else {
                [self showAlert:@"发送命令失败,请检查网络"];
                block(NO);
            }
        }];
    }else {
        block(NO);
    }
}

- (void)playNext:(void(^)(BOOL success))block {
    self.playIndex ++;
    if (self.playIndex >= self.musicModelArr.count) {
        self.playIndex = 0;
    }
    [self play:block];
}

- (void)updateLogAtSingleMode:(BOOL)singleMode {
    
    if (singleMode) {
        
        FGMusicModel *model = [self currentPlayMusicModel];
        [self.log appendString:@"\n\n=========="];
        [self.log appendString:[NSString stringWithFormat:@"\n距离:%@  ,角度:%@  ,模式:%@  ,播放次数:%@  ,实际播放次数:%ld", self.distanceTextField.text, self.angleTextField.text, self.modeSegmentedControl.selectedSegmentIndex == 0 ? @"单曲":@"顺序", self.timesTextField.text, (long)self.allPlayCount]];
        NSString *successedRateStr = [NSString stringWithFormat:@"\n唤醒率 : %.0f%%",(1.0 * model.successCount)/model.playedCount * 100];
        NSString *detailStr = [NSString stringWithFormat:@"\n%@ -- 失败 %d 次",model.name, (model.playedCount - model.successCount)];
        [self.log appendString:successedRateStr];
        [self.log appendString:detailStr];
        [self.log appendString:@"\n=========="];
        
    }else {
        
        NSMutableString *tempStr = [NSMutableString string];
        int successedCount = 0;
        for (FGMusicModel *model in self.musicModelArr) {
            successedCount += model.successCount;
            NSString *detailStr = [NSString stringWithFormat:@"\n%@ -- 失败 %d 次",model.name, (model.playedCount - model.successCount)];
            [tempStr appendString:detailStr];
        }
        [self.log appendString:@"\n\n=========="];
        [self.log appendString:[NSString stringWithFormat:@"\n距离:%@  ,角度:%@  ,模式:%@  ,播放次数:%@  ,实际播放次数:%ld", self.distanceTextField.text, self.angleTextField.text, self.modeSegmentedControl.selectedSegmentIndex == 0 ? @"单曲":@"顺序", self.timesTextField.text, (long)self.allPlayCount]];
        NSString *successedRateStr = [NSString stringWithFormat:@"\n唤醒率 : %.0f%%",(1.0 * successedCount) / self.allPlayCount * 100];
        [self.log appendString:successedRateStr];
        [self.log appendString:tempStr];
        [self.log appendString:@"\n=========="];
    }
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:LogSegueIdentifier]) {
        FGLogViewController *vc = segue.destinationViewController;
        vc.log = self.log;
    }else if ([segue.identifier isEqualToString:MixPadSegueIdentifier]) {
        FGMixPadTableViewController *vc = segue.destinationViewController;
        vc.vc = self;
        vc.allMixPadArr = [self allMixPadInFamily];
    }
}

#pragma mark - others

- (void)startCountDown:(void (^)(NSTimer *timer))block {
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    self.countDown = CountDownTime;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:block];
}

- (FGMusicModel *)currentPlayMusicModel {
    if (self.playIndex >= 0 && self.playIndex < self.musicModelArr.count) {
        FGMusicModel *model = self.musicModelArr[self.playIndex];
        return model;
    }
    return nil;
}

- (BOOL)isDirectory:(NSString *)filePath
{
    BOOL isDirectory = NO;
    [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDirectory];
    return isDirectory;
}

- (void)showAlert:(NSString *)str {
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:str preferredStyle:UIAlertControllerStyleAlert];
    //添加确定
    UIAlertAction *sureBtn = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull   action) {
        if ([str isEqualToString:@"请先选择MixPad"]) {
            [self performSegueWithIdentifier:MixPadSegueIdentifier sender:self];
        }else if ([str isEqualToString:@"MixPad无响应"]) {
            [self performSegueWithIdentifier:LogSegueIdentifier sender:self];
        }else if ([str isEqualToString:@"发送命令失败,请检查网络"]) {
            [self performSegueWithIdentifier:LogSegueIdentifier sender:self];
        }
    }];

    [alertVc addAction :sureBtn];
    //展示
    [self presentViewController:alertVc animated:YES completion:nil];
}

//家庭中的mixpad
- (NSArray <HMDevice *>*)allMixPadInFamily {
    NSString *sql = [NSString stringWithFormat:@"select * from device where uid in %@ and delFlag = 0 and deviceType = %d order by createTime asc",[HMUserGatewayBind uidStatement], KDeviceTypeMixPad];
    
    __block NSMutableArray *devicesArr = [NSMutableArray array];
    queryDatabase(sql, ^(FMResultSet *rs) {
        HMDevice *device = [HMDevice object:rs];
        [devicesArr addObject:device];
    });
    
    return devicesArr;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    [self.view endEditing:YES];
}

@end
